<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-12-02 18:34:49
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-27 16:30:58
-->
<template>
  <x-page class="flex-row">
    <div class="left-panel">
      <div class="top">
        <el-dropdown style="margin-right: 15px" @command="handleCommand" v-hasPermi="['upms:post:add']">
          <el-button type="primary" plain>
            {{ $t('organization.post.add') }}<em class="el-icon-arrow-down el-icon--right"></em
          ></el-button>
          <el-dropdown-menu>
            <el-dropdown-item command="a">{{ $t('organization.post.addRoot') }}</el-dropdown-item>
            <el-dropdown-item command="b">{{ $t('organization.post.newSubPost') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!-- <el-button type="primary" plain @click="handleExpand"
          ><em class="el-icon-s-operation"></em>{{ isExpanded ? '全部收起' : '全部展开' }}</el-button
        > -->
      </div>
      <div class="tree-container">
        <div class="search-input-container">
          <el-input
            prefix-icon="el-icon-search"
            :placeholder="$t('common.treeFilter')"
            v-model="filterText"
            clearable
            style="margin-bottom: 20px"
          >
          </el-input>
        </div>

        <el-scrollbar
          style="height: calc(100% - 60px)"
          v-loading="treeLoading"
          :element-loading-text="$t('common.loading')"
          element-loading-spinner="el-icon-loading"
        >
          <el-tree
            :props="treeProps"
            ref="tree"
            node-key="id"
            :key="treeKey"
            default-expand-all
            :highlight-current="true"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :data="postTreeData"
            :render-content="renderContent"
            @node-click="handleNodeClick"
          ></el-tree>
        </el-scrollbar>
      </div>
    </div>
    <div class="right-panel">
      <div class="info-hearder flex-column">
        <div class="h3" v-if="currentNode?.postName">
          <span>{{ currentNode?.postName ?? '' }}</span>
          <el-button round size="small" @click="handleAddPost(currentNode)" style="margin-left: 8px">
            {{ $t('common.edit') }}
          </el-button>
          <el-button round size="small" @click="handleDeletePrm(currentNode)" style="margin-left: 8px">
            {{ $t('common.delete') }}
          </el-button>
        </div>
        <el-breadcrumb separator-class="el-icon-arrow-right" v-if="currentNode?.path" class="sub-title">
          <el-breadcrumb-item v-for="(ele, eleIndex) in currentNode.path" :key="eleIndex">{{ ele }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <h4 class="sub_title">
        <em class="iconfont icon-a-Property1zuzhipeizhi"></em>
        {{ $t('organization.post.subPost') }}
      </h4>
      <!-- <el-alert :title="$t('organization.post.postInfoTips')"
                type="info"
                show-icon
                style="margin-bottom: 10px;">
      </el-alert> -->
      <!--数据面板-->
      <x-data>
        <!--数据面板按钮插糟-->
        <template #tool>
          <el-row type="flex" class="tools" justify="space-between">
            <el-col :span="18">
              <el-button
                v-hasPermi="['upms:post:add']"
                v-if="currentNode?.postName"
                round
                size="small"
                @click="handleAddPost({ parentId: currentNode.id, deptId: currentNode.deptId })"
              >
                {{ $t('organization.post.newSubPost') }}
              </el-button>
              <el-button
                v-hasPermi="['upms:post:exportExcel']"
                v-if="currentNode?.postName"
                round
                size="small"
                @click="handleExportPost()"
              >
                {{ $t('organization.post.export') }}
              </el-button>
            </el-col>
            <el-col :span="6" class="tools-config">
              <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
            </el-col>
          </el-row>
        </template>
        <x-table
          ref="tableCom"
          :pagination="pagination"
          :data-source="tableData"
          :loading="loading"
          :row-key="'id'"
          @on-change="handleTableChange"
        >
          <el-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :prop="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :min-width="item.minWidth || '-'"
            :width="item.width"
            :label="item.label"
            :sortable="'custom'"
          >
            <template #default="scope">
              <el-switch
                v-if="item.prop === 'state'"
                :value="scope.row[item.prop]"
                active-color="#4474F6"
                inactive-color="#A5A9B2"
                :disabled="!checkBntPermi('upms:post:state')"
                @change="handleChangeState(scope.row[item.prop], scope.row.id)"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
              <span v-else-if="item.prop === 'roles'">
                {{ getRoleName(scope.row[item.prop]) }}
              </span>
              <span v-else-if="item.prop === 'postRank'">
                {{ getDictLabel(dictOptions['upms_post.post_rank'], scope.row[item.prop]) }}
              </span>
              <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('common.opeartion')" :align="'center'" width="160">
            <template #default="scope">
              <more-table-actions
                :action-list="actions"
                :permis-list="permissionsActions"
                :row="scope.row"
                @onActionClick="handleActions"
              />
            </template>
          </el-table-column>
        </x-table>
      </x-data>
    </div>
    <!-- 岗位信息弹窗 -->
    <post-add
      ref="postAddComponent"
      :dict-options="dictOptions"
      :post-tree-options="postTreeData"
      :default-post-props="treeProps"
      @handleSuccess="loadTreeData"
      @on-delete="handleDeletePost"
    ></post-add>
  </x-page>
</template>
<script lang="jsx">
  // import { TableListMixin, QueryDictMixin, PermissionsMixin } from '@/common/mixins'
  import { selectDictLabel, TableListMixin, QueryDictMixin, PermissionsMixin } from '@package/utils'
  import { mapState } from 'pinia'
  import { pinias } from '@/common/pinia'
  import {
    postPageListUrl,
    apiPostTree,
    apiDeletePost,
    apiPutDisablePost,
    apiPutEnablePost,
    postExportUrl
  } from '../api'
  import PostAdd from '../components/postAdd.vue'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import { columns, actions } from '../config/postConfig.js'

  const { cachedView } = pinias
  export default {
    name: 'Post',
    components: {
      PostAdd
    },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        postPageListUrl,
        postExportUrl,
        columns,
        actions,
        disableMixinCreated: true,
        creatFlag: false,
        filterText: '',
        currentNode: {},
        treeProps: {
          label: 'postName',
          children: 'children'
        },
        treeKey: '1',
        postTreeData: [],
        dictKeys: ['system.state', 'upms_post.post_rank'],
        treeLoading: false
      }
    },
    computed: {
      ...mapState(cachedView, ['visitedViews']),
      listUrl() {
        return this.postPageListUrl
      },
      getRoleName() {
        return (val) => {
          if (val?.length) {
            return val.map((v) => v.roleName).join(',')
          }
          return ''
        }
      },
      otherParam() {
        return { parentId: this.currentNode?.id ?? '' }
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    mounted() {
      this.creatFlag = true
      this.loadTreeData()
      this.initDictConfig()
    },
    activated() {
      const temp = this.visitedViews.filter((v) => v.path === this.$route.path)
      if (this.disableMixinCreated && this.creatFlag && !temp) {
        this.loadTreeData()
      }
    },
    methods: {
      getDictLabel(list, value) {
        return selectDictLabel(list, value) || '-'
      },
      async loadTreeData() {
        this.treeLoading = true
        this.postTreeData = []
        const { data, code, msg } = await apiPostTree()
        this.treeLoading = false
        if (code === EnumApiCode.Success) {
          this.postTreeData = data
          if (!this.currentNode && this.postTreeData?.length) {
            this.currentNode = this.postTreeData[0]
          }
          this.treeKey = Math.random()
          this.$nextTick(() => {
            this.refrenTreeCurrent(this.currentNode.id)
          })
        } else {
          this.$message.error(msg)
        }
      },
      refrenTreeCurrent(key) {
        this.$nextTick(() => {
          // 双重判定，历史选中节点是否存在于树节点上
          const isCheck = this.$refs.tree.getNode(key)
          if (!isCheck) {
            this.currentNode = this.postTreeData[0]
          }
          this.$refs.tree.setCurrentKey(this.currentNode.id)
          const data = this.$refs.tree.getCurrentNode()
          const node = this.$refs.tree.getNode(this.currentNode.id)
          this.handleNodeClick(data, node)
        })
      },
      async handleChangeState(state, id) {
        const { code, msg } = state === 1 ? await apiPutDisablePost(id) : await apiPutEnablePost(id)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('system.user.successTips'))
          this.handleSearch()
        } else {
          this.$message.error(msg)
        }
      },
      filterNode(value, data) {
        if (!value) return true
        return data[this.treeProps.label].indexOf(value) !== -1
      },
      handleNodeClick(data, node, ele) {
        this.currentNode = JSON.parse(JSON.stringify(data))
        if (node.parent.data.id) {
          this.currentNode.path = [node.parent.data.postName, this.currentNode.postName]
        }
        this.handleSearch()
      },
      renderContent(h, { node, data, store }) {
        let nodeClass = ''
        if (data.state === 0) {
          nodeClass = 'gray'
        }
        return (
          <div className="custom-tree-node">
            <span className={nodeClass} title={node.label}>
              {node.label}
            </span>
          </div>
        )
      },
      handleCommand(command) {
        if (command === 'a') {
          this.$refs.postAddComponent.handleOpen({ parentId: 0 }, false)
        } else if (command === 'b') {
          this.$refs.postAddComponent.handleOpen({ parentId: this.currentNode.id, deptId: this.currentNode.deptId })
        }
      },
      handleAddPost(info) {
        this.$refs.postAddComponent.handleOpen(info)
      },
      handleExportPost() {
        this.handleExport(this.postExportUrl)
      },
      handleActions({ key, data }) {
        switch (key) {
          case 'edit': // 修改岗位基本信息
            this.$refs.postAddComponent.handleOpen(data)
            break
          case 'delete':
            this.$confirm(this.$t('system.user.deleteSure'), this.$t('system.user.deletePrompt'), {
              confirmButtonText: this.$t('common.confirm'),
              cancelButtonText: this.$t('common.cancel'),
              type: 'warning'
            })
              .then((confirm) => {
                this.handleDeletePost(data.id)
              })
              .catch((cancel) => {})
            break
          case 'allotRole': // 岗位分配角色
            this.$refs.postAuthtComponent.handleOpen(data)
            break
          default:
            break
        }
      },
      handleDeletePrm(data) {
        this.$confirm(this.$t('system.user.deleteSure'), this.$t('system.user.deletePrompt'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        })
          .then((confirm) => {
            this.handleDeletePost(data.id)
          })
          .catch((cancel) => {})
      },
      /**
       * 删除岗位的请求
       * @param postId 岗位ID string
       */
      async handleDeletePost(postId) {
        const { code } = await apiDeletePost(postId)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('system.user.successTips'))
          await this.loadTreeData()
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../../common/assets/style/variables';

  .flex-row {
    display: flex;
    flex-direction: row;

    .left-panel {
      flex: 1;
      min-width: 300px;
      border-radius: 3px;
      background-color: $x-default-bg-color;

      .top {
        margin-bottom: 16px;
        padding: 12px 15px;
        border-bottom: 1px solid #e0e0e0;
      }

      .tree-container {
        height: calc(100% - 100px);
        .search-input-container {
          padding: 0 15px;
        }
      }
    }

    .right-panel {
      display: flex;
      flex: 5;
      flex-direction: column;
      max-width: calc(100% - 300px);
      margin-left: 10px;
      color: #424242;
      border-radius: 3px;
      background-color: $x-default-bg-color;

      h4,
      .h3 {
        font-size: 20px;
        font-weight: 500;
        margin: 0;
        // padding: 0 20px;

        span {
          line-height: 30px;
        }
      }

      h4 {
        margin-bottom: 19px;
        padding: 0 20px;

        .iconfont {
          font-size: 20px;
        }
      }

      h3 {
        padding-top: 20px;
      }

      .el-breadcrumb.sub-title {
        font-size: 14px;
        line-height: 36px;
        padding-left: 7px;
      }

      .x-data-view {
        margin-top: 0;
        padding-top: 0;
        border-width: 0;
      }

      .tools {
        line-height: 42px;
        padding: 0 15px;
        border-radius: 3px;
        background-color: #eceff4;
      }

      .info-container {
        padding: 0 15px;
      }

      .info-hearder {
        font-size: 16px;
        // line-height: 60px;
        // margin-bottom: 10px;
        padding: 15px;
        color: $x-item-text-color;
        // border-bottom: 1px solid #e0e0e0;

        .el-icon-edit-outline {
          font-size: 18px;
          vertical-align: middle;
        }
      }
    }
  }
</style>
<style lang="scss">
  /* element滚动条组件 隐藏水平滚动条 */
  .tree-container .el-scrollbar__view {
    padding: 0 15px;
  }
  .tree-container .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  .is-horizontal {
    display: none;
  }
</style>
